import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'

export const useStore = create(
  persist(
    (set, get) => ({
  // 当前步骤：1-上传图片, 2-生成中, 3-预览下单
  currentStep: 1,
  
  // 上传的图片
  uploadedImage: null,
  uploadedImageFile: null,
  
  // 3D模型数据
  modelUrl: null,
  modelData: null,
  
  // 版本号，用于清除旧的演示模式数据
  _storeVersion: 2,
  
  // 生成状态
  isGenerating: false,
  generationProgress: 0,
  
  // 订单信息
  orderInfo: {
    quantity: 1,
    material: 'pla',
    color: 'white',
    customColor: '#FFFFFF',
    size: 'medium'
  },
  
  // 订单列表
  orders: [],
  
  // 收货地址列表
  addresses: [],

  // Actions
  setCurrentStep: (step) => set({ currentStep: step }),
  
  setUploadedImage: (image, file) => set({ 
    uploadedImage: image,
    uploadedImageFile: file,
    currentStep: 1
  }),
  
  setModelData: (url, data) => set({ 
    modelUrl: url,
    modelData: data,
    currentStep: 3
  }),
  
  setGenerating: (status) => set({ isGenerating: status }),
  
  setGenerationProgress: (progress) => set({ generationProgress: progress }),
  
  updateOrderInfo: (info) => set((state) => ({
    orderInfo: { ...state.orderInfo, ...info }
  })),
  
  // 添加订单
  addOrder: (order) => set((state) => ({
    orders: [order, ...state.orders]
  })),
  
  // 取消订单
  cancelOrder: (orderId) => set((state) => ({
    orders: state.orders.map(order =>
      order.id === orderId
        ? { ...order, status: 'cancelled' }
        : order
    )
  })),
  
  // 更新订单状态
  updateOrderStatus: (orderId, status) => set((state) => ({
    orders: state.orders.map(order =>
      order.id === orderId
        ? { ...order, status }
        : order
    )
  })),
  
  // 获取订单
  getOrder: (orderId) => (state) => 
    state.orders.find(order => order.id === orderId),
  
  
  // 地址相关
  addAddress: (address) => set((state) => ({
    addresses: [...state.addresses, { ...address, id: Date.now().toString() }]
  })),
  
  updateAddress: (addressId, updates) => set((state) => ({
    addresses: state.addresses.map(addr =>
      addr.id === addressId ? { ...addr, ...updates } : addr
    )
  })),
  
  deleteAddress: (addressId) => set((state) => ({
    addresses: state.addresses.filter(addr => addr.id !== addressId)
  })),
  
  setDefaultAddress: (addressId) => set((state) => ({
    addresses: state.addresses.map(addr => ({
      ...addr,
      isDefault: addr.id === addressId
    }))
  })),
  
  resetAll: () => set({
    currentStep: 1,
    uploadedImage: null,
    uploadedImageFile: null,
    modelUrl: null,
    modelData: null,
    isGenerating: false,
    generationProgress: 0,
    orderInfo: {
      quantity: 1,
      material: 'pla',
      color: 'white',
      customColor: '#FFFFFF',
      size: 'medium'
    }
    // 注意：不重置 orders，保留订单历史
  })
}),
    {
      name: '3d-platform-storage', // localStorage key
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        // 只持久化这些数据
        orders: state.orders,
        orderInfo: state.orderInfo,
        addresses: state.addresses,
        _storeVersion: state._storeVersion
        // 不持久化临时状态：uploadedImage, modelUrl, isGenerating 等
      }),
      // 迁移函数：清除旧的演示模式数据
      migrate: (persistedState, version) => {
        if (!persistedState._storeVersion || persistedState._storeVersion < 2) {
          // 清除旧的演示模式数据
          console.log('🧹 检测到旧版本数据，正在清理...')
          return {
            ...persistedState,
            _storeVersion: 2
          }
        }
        return persistedState
      },
      version: 2
    }
  )
)

